# from bs4 import BeautifulSoup
import os

from tools import security_url_get
from icalendar import Calendar
import pandas as pd

# def fetch_top4_conf_countdown():
#     # https://sec-deadlines.github.io/ical/deadlines-all.ical
#     ical_url = "https://sec-deadlines.github.io/ical/deadlines-all.ical"
#     response = security_url_get(ical_url)
#     if not response:
#         return None
#     # soup = BeautifulSoup(response.text, "html.parser")
#     # print(soup)
#     gcal = Calendar.from_ical(response.content)
#     # 3. 遍历事件
#     events = []
#     for component in gcal.walk():
#         if component.name == "VEVENT":
#             # events.append({
#             #     "summary": str(component.get("summary")),
#             #     "start": component.get("dtstart").dt,
#             #     "end": component.get("dtend").dt,
#             #     "location": str(component.get("location")),
#             #     "description": str(component.get("description")),
#             #     "url": str(component.get("url")) if component.get("url") else ""
#             # })
#             # BEGIN:VEVENT
#             # UID:s-p-oakland-2026-0@sec-deadlines.github.io
#             # SUMMARY:S&P (Oakland) 2026 Deadline (1 / 2)
#             # DESCRIPTION:Deadline for S&P (Oakland) 2026 May 18-21 San Francisco, California, USA\n
#             # IEEE Symposium on Security and Privacy\n\n
#             # https://sp2026.ieee-security.org/
#             # URL:https://sp2026.ieee-security.org/
#             # LOCATION:San Francisco, California, USA
#             # CLASS:PUBLIC
#             # DTSTAMP:20250707T17251751909137Z
#             # DTSTART;TZID=Etc/GMT+12:20250605T235900
#             # DTEND;TZID=Etc/GMT+12:20250605T235959
#             # END:VEVENT
#             print(f"vevent: {component.get('summary')},"
#                   f" start: {component.get('dtstart').dt}, "
#                   f"end: {component.get('dtend').dt}, "
#                   f"location: {component.get('location')}, "
#                   f"url: {component.get('url')}")
#     # # 4. 转为 DataFrame
#     # df = pd.DataFrame(events)
#     # df = df.sort_values(by="start").reset_index(drop=True)
#     #
#     # # 5. 显示前几条记录
#     # print(df.head())
#
#
#
#     return response.text if response else None
import requests
from icalendar import Calendar
from datetime import datetime
import pytz
import pandas as pd

def fetch_top4_conf_countdown(file_path,
                              filter=['IEEE Symposium on Security and Privacy',
                                      'ACM Conference on Computer and Communications Security',
                                      'USENIX Security Symposium',
                                      'Network and Distributed System Security Symposium'
                                      ]):
    # response = requests.get(ical_url)
    # response.raise_for_status()
    # response = security_url_get(ical_url)
    # if not response:
    #     return None
    with open(file_path, "rb") as f:
        gcal = Calendar.from_ical(f.read())

        events = []
        for component in gcal.walk():
            if component.name == "VEVENT":
                summary = str(component.get("SUMMARY"))
                description = component.get("DESCRIPTION")
                dtend = component.get("DTEND").dt
                location = str(component.get("LOCATION"))
                url = str(component.get("URL")) if component.get("URL") else ""

                if not any(f in str(description) for f in filter):
                    continue


                # 强制将时间转为带时区的 datetime 对象
                if isinstance(dtend, datetime) and dtend.tzinfo is None:
                    dtend = pytz.utc.localize(dtend)

                # 转换为北京时间（UTC+8）
                beijing_tz = pytz.timezone("Asia/Shanghai")
                dtend_bj = dtend.astimezone(beijing_tz)
                now_bj = datetime.now(beijing_tz)

                # 过滤已经过期的会议
                if dtend_bj < now_bj:
                    continue

                # 当前北京时间
                # now_bj = datetime.now(beijing_tz)
                days_left = (dtend_bj.date() - now_bj.date()).days

                events.append({
                    "Conference": summary,
                    "Location": location,
                    "Deadline": dtend_bj.strftime("%Y-%m-%d %H:%M"),
                    "Days Left": days_left,
                    "URL": url
                })
    return events

# # 主函数调用
# if __name__ == "__main__":
#     ical_url = "https://sec-deadlines.github.io/deadlines.ical"
#     df = fetch_and_parse_ical(ical_url)
#
#     # 输出前几个即将截止的会议
#     print(df.head(10))

def update_ical_url(ical_url = "https://sec-deadlines.github.io/ical/deadlines-all.ical", save_file="data", save_name="deadlines-all.ical"):
    # ical_url = "https://sec-deadlines.github.io/ical/deadlines-all.ical"
    # save_path = "deadlines-all.ical"
    response = security_url_get(ical_url)
    if response:
        save_path = os.path.join(save_file, save_name)
        if not os.path.exists(save_file):
            os.makedirs(save_file, exist_ok=True)
        with open(save_path, "wb") as f:
            f.write(response.content)
        return save_path
    else:
        print(f"Failed to fetch the iCal file from {ical_url}")
        return None

if __name__ == '__main__':

    save_path = update_ical_url()
    if not save_path:
        print("Failed to update the iCal file.")
        exit(1)
    else:
        print(f"iCal file saved to {save_path}")
    res = fetch_top4_conf_countdown(save_path)
    # print(res)
    for r in res:
        print(f"Conference: {r['Conference']}, "
              f"Location: {r['Location']}, "
              f"Deadline (Beijing Time): {r['Deadline']}, "
              f"Days Left: {r['Days Left']}, "
              f"URL: {r['URL']}")